package Test;

import java.util.concurrent.Executors;

public class Test {


    public static void main(String[] args) {
        System.out.println(trans(""));
        System.out.println(trans(" "));
        System.out.println(trans("isTrue"));
        System.out.println(trans("myFirstName"));
        System.out.println(trans("OnlineUsers"));
        System.out.println(trans("Address"));
        System.out.println(trans("validHTTPRequest"));
        System.out.println(trans("ValidHTTPSRequestCall"));
        System.out.println(trans("UsingHTTPS"));
    }


    /**
     * 双指针法
     * l之前的表示已经转换过的字符
     * l-r之间的表示需要被转换的单词
     * r之后表示还没有循环到的字符
     *
     * @param s 传入的字符串
     * @return
     */
    public static StringBuilder trans(String s) {
        StringBuilder stringBuilder = new StringBuilder();
        int l = 0;
        int r = 0;
        while (r < s.length()) {
            //如果下一个字符是小写
            if (r + 1 < s.length() && !isUpper(s.charAt(r + 1))) {
                while (true) {
                    r++;
                    if (r == s.length()) {
                        stringBuilder.append(s.substring(l).toLowerCase());
                        return stringBuilder;
                    }
                    if (isUpper(s.charAt(r))) {
                        stringBuilder.append(s.substring(l, r).toLowerCase() + "_");
                        l = r;
                        break;
                    }
                }
            } else if (r + 1 < s.length()) {//如果下个字符是连着的大写 如HTTP
                //判断是不是第一个字符，如果不判断则会出现aA 变为aa的情况 而不是a_a
                if (r == 0 && isUpper(s.charAt(r + 1))) {
                    r++;
                    stringBuilder.append(s.substring(l, r).toLowerCase() + "_");
                    l = r;
                } else {
                    while (true) {
                        r++;
                        if (r == s.length()) {
                            stringBuilder.append(s.substring(l).toLowerCase());
                            return stringBuilder;
                        }
                        if (!isUpper(s.charAt(r))) {
                            r--;
                            stringBuilder.append(s.substring(l, r).toLowerCase() + "_");
                            l = r;
                            break;
                        }
                    }
                }
            } else {//如果是到达最后了
                stringBuilder.append(s.substring(l).toLowerCase());
                r++;
            }
        }
        return stringBuilder;
    }

    public static boolean isUpper(char c) {
        return c >= 'A' && c <= 'Z';
    }
}
